package com.card.controller;

import com.card.entity.CardInfo;
import com.card.service.CardInfoService;
import com.card.utils.JwtUtils;
import com.card.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/card")
public class CardInfoController {

    @Resource
    private CardInfoService cardInfoService;

    /**
     * 获取名片信息
     * @param request
     * @return
     */
    @GetMapping("/getCardInfo")
    public Result<CardInfo> getCardInfo(HttpServletRequest request) {
        String token = request.getHeader(JwtUtils.header);
        String openId = JwtUtils.validateToken(token);
        CardInfo cardInfo = cardInfoService.getCardInfo(openId);
        return Result.success(cardInfo);
    }

    /**
     * 保存名片信息
     * @param request
     * @param cardInfo
     * @return
     */
    @PostMapping("/add")
    public Result<Boolean> add(HttpServletRequest request, @RequestBody CardInfo cardInfo) {
        if (Objects.isNull(cardInfo.getId())) {
            String token = request.getHeader(JwtUtils.header);
            String openId = JwtUtils.validateToken(token);
            cardInfo.setOpenId(openId);
            boolean flag = cardInfoService.save(cardInfo);
            return Result.success(flag);
        } else {
            boolean flag = cardInfoService.updateById(cardInfo);
            return Result.success(flag);
        }

    }

    /**
     * 判断当前openId和页面信息所属的openId是否一致
     * @param request
     * @return
     */
    @GetMapping("check")
    public Result<Boolean> check(HttpServletRequest request, String openId) {
        String token = request.getHeader(JwtUtils.header);
        String myOpenId = JwtUtils.validateToken(token);
        if (myOpenId.equals(openId)) {
            return Result.success(true);
        } else {
            return Result.success(false);
        }
    }

}
